package com.rem.concurrency.juc.my15Lock;

import cn.hutool.core.util.RandomUtil;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Lock版本 可重入锁
 *
 * @author Rem
 * @date 2021-03-11
 */

public class ReentryLockDemo {

    public static void main(String[] args) {
        Phone2 phone2 = new Phone2();


        for (int i = 0; i < 20; i++) {
            new Thread(() -> {
                phone2.sms();
            }, RandomUtil.randomString(4)).start();
        }

    }
}


class Phone2 {

    private ReentrantLock lock = new ReentrantLock();

    public void sms() {

        lock.lock();

        try {
            System.out.println(Thread.currentThread().getName() + ":==>sms");
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 这里也有锁
            call();
        } finally {
            lock.unlock();
        }
    }

    public void call() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + ":==>call");
        } finally {
            lock.unlock();
        }
    }
}